#include <jni.h>
#include <string>

#include <dlfcn.h>

extern "C" JNIEXPORT jstring JNICALL
Java_cso_loadso_MainActivity_stringFromJNI(
        JNIEnv* env,
        jobject /* this */) {
    std::string hello = "Hello from C++";
    return env->NewStringUTF(hello.c_str());
}


extern "C"
JNIEXPORT jstring JNICALL
Java_cso_loadso_MainActivity_helloSo(JNIEnv *env, jobject thiz, jstring file_dir_path) {
    // TODO: implement helloSo()

    // 将 Java 字符串转换为 C 字符串
    const char *path = env->GetStringUTFChars(file_dir_path, nullptr);

    std::string hello = std::string(path);
    hello.append("/libadd.so");

    const char* libPath = hello.c_str();

    void* handle = dlopen(libPath, RTLD_NOW);
    if (!handle) {
        // 加载失败，打印错误信息
        const char* error = dlerror();
        // 处理错误
        hello.append(" fail ");
        hello.append(error);
    }else {
        hello.append(" success ");

        if (true) {
            typedef int (*goFunc)();
            goFunc f = (goFunc) dlsym(handle, "Java_a_myapp_MainActivity_StringFromGo");
            if (f) {
                hello.append(" 1 ");
                f();
            } else {
                hello.append(" 2 ");
            }
        }
    }

    // std::string hello = "Hello from CC++";
    return env->NewStringUTF(hello.c_str());
}